package testndk.testservice;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import testndk.testserviceaidl.ICountService;

public class AIDLClientActivity extends Activity {
    private static final int TIME = 1;
    private Button startBtn = null;
    private Button stopBtn = null;
    private TextView mTextView = null;
    private ProgressBar mProgressBar = null;
    private boolean mIsBind;
    private Timer mTimer = null;
	/**获取ICountService实例*/
    private ICountService iCountService = null;
	/**开启服务的显示意图*/
	private Intent eintent;

	Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			try {
				int count =  iCountService.getCount();
				mTextView.setText(count+"%");
				mProgressBar.setProgress(count);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
    };
	private ServiceConnection serConn = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			iCountService = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			iCountService = ICountService.Stub.asInterface(service);
		}
	};

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mTimer = new Timer();
		Intent intent = new Intent("testndk.testserviceaidl.AIDLServer");
		//把隐式意图转为显示意图
		eintent = new Intent(createExplicitFromImplicitIntent(this,intent));
		mTextView = (TextView)findViewById(R.id.loading_Tv);
        mProgressBar = (ProgressBar)findViewById(R.id.myProgressBar);
        mProgressBar.setMax(100);
        startBtn = (Button)findViewById(R.id.start_Btn);
        stopBtn = (Button)findViewById(R.id.stop_Btn);
        startBtn.setOnClickListener(new ButtonClickListener());
        stopBtn.setOnClickListener(new ButtonClickListener());

    }

    class ButtonClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			if(startBtn==v){
				mIsBind = bindService(eintent, serConn, BIND_AUTO_CREATE);
				if (mTimer == null){
					mTimer = new Timer();
				}
				mTimer.schedule(new MyTimerTask(), 1000 ,TIME * 1000);
			}else if (stopBtn==v) {
				if(mIsBind){
					unbindService(serConn);
					if(mTimer!=null){
						mTimer.cancel();
						mTimer = null;
					}
					mIsBind = false;
				}
			}
		}
    	
    }
    
    class MyTimerTask extends TimerTask{
		@Override
		public void run() {
			mHandler.sendMessage(mHandler.obtainMessage());
		}
    }


	/***
	 * Android L (lollipop, API 21) introduced a new problem when trying to invoke implicit intent,
	 * "java.lang.IllegalArgumentException: Service Intent must be explicit"
	 *
	 * If you are using an implicit intent, and know only 1 target would answer this intent,
	 * This method will help you turn the implicit intent into the explicit form.
	 *
	 * Inspired from SO answer: http://stackoverflow.com/a/26318757/1446466
	 * @param context
	 * @param implicitIntent - The original implicit intent
	 * @return Explicit Intent created from the implicit original intent
	 */
	public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) {
		// Retrieve all services that can match the given intent
		PackageManager pm = context.getPackageManager();
		List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);

		// Make sure only one match was found
		if (resolveInfo == null || resolveInfo.size() != 1) {
			return null;
		}

		// Get component info and create ComponentName
		ResolveInfo serviceInfo = resolveInfo.get(0);
		String packageName = serviceInfo.serviceInfo.packageName;
		String className = serviceInfo.serviceInfo.name;
		ComponentName component = new ComponentName(packageName, className);

		// Create a new intent. Use the old one for extras and such reuse
		Intent explicitIntent = new Intent(implicitIntent);

		// Set the component to be explicit
		explicitIntent.setComponent(component);

		return explicitIntent;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mTimer!=null){
			mTimer.cancel();
			mTimer = null;
		}
		if (mIsBind){
			unbindService(serConn);
		}
	}

}